import { LocalStorage } from '@/utils/utils';

import { cloneDeep, isNull } from 'lodash-es';
import { defineStore } from 'pinia';
import { ref } from 'vue';

const TAG_NAV_KEY = 'tag_nav';

import type {
  LocationQuery,
  RouteLocationNormalizedGeneric,
  RouteLocationNormalizedLoadedGeneric,
  RouteRecordNameGeneric,
} from 'vue-router';

export type TagNav = {
  menuName: string;
  menuTitle: unknown;
  menuQuery?: LocationQuery;
  menuIcon?: unknown;
  fromMenuName?: RouteRecordNameGeneric;
  fromMenuQuery?: LocationQuery;
};

export const TagNavStore = defineStore('tagNav', () => {
  // 获取标签导航
  const tagNav = ref<TagNav[] | null>(null);

  function getTagNav() {
    if (isNull(tagNav.value)) {
      const localTagNav = LocalStorage.get(TAG_NAV_KEY) || '';
      tagNav.value = localTagNav ? JSON.parse(localTagNav) : [];
    }
    const tagNavList = cloneDeep(tagNav.value) || [];
    tagNavList.unshift({
      menuName: 'Home',
      menuTitle: '首页',
    });
    return tagNavList;
  }
  //设置标签页
  function setTagNav(route: RouteLocationNormalizedGeneric, from: RouteLocationNormalizedLoadedGeneric) {
    if (isNull(tagNav.value)) {
      const localTagNav = LocalStorage.get(TAG_NAV_KEY) || '';

      tagNav.value = localTagNav ? JSON.parse(localTagNav) : [];
    }
    // name唯一标识
    const name = route.name;
    if (!name || name === 'Home' || name === '403' || name === '404') {
      return;
    }
    const findTag = (tagNav.value || []).find((e) => e.menuName === name);
    if (findTag) {
      findTag.fromMenuName = from.name;
      findTag.fromMenuQuery = from.query;
    } else if (!route.meta.hideInMenu) {
      const tag = {
        menuName: name as string,
        menuTitle: route.meta.title,
        menuQuery: route.query,
        menuIcon: route.meta?.icon,
        fromMenuName: from.name,
        fromMenuQuery: from.query,
      };
      const array = tagNav.value || [];
      array.push(tag);
      tagNav.value = array;
    }
    LocalStorage.set(TAG_NAV_KEY, JSON.stringify(tagNav.value));
  }
  //关闭标签页
  function closeTagNav(menuName: string, closeAll: boolean) {
    if (closeAll && !menuName) {
      tagNav.value = [];
    } else {
      const findIndex = (tagNav.value || []).findIndex((e) => e.menuName === menuName);
      if (closeAll) {
        if (findIndex === -1) {
          tagNav.value = [];
        } else {
          const tagNavElement = (tagNav.value || [])[findIndex];
          tagNav.value = [tagNavElement];
        }
      } else {
        (tagNav.value || []).splice(findIndex, 1);
      }
    }
    LocalStorage.set(TAG_NAV_KEY,JSON.stringify(tagNav.value));
  }

  return {
    tagNav,
    getTagNav,
    setTagNav,
    closeTagNav,
  };
});
